package com.cc.bill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cc.bill.entity.SubmitBillCertificatePictureEntity;
import com.cc.bill.entity.SubmitBillDetailEntity;
import com.cc.bill.entity.SubmitBillEntity;
import com.cc.bill.entity.SubmitBillNameEntity;
import com.cc.bill.service.SubmitBillCertificatePictureService;
import com.cc.bill.service.SubmitBillNameService;
import com.cc.bill.service.SubmitBillService;
import com.cc.bill.vo.SubmitBillVo;
import com.cc.bill.vo.SubmitSelectConditionVo;
import com.cc.bill.vo.UploadSubmitBillVo;
import com.cc.bill.vo.WebBillVo;
import com.cc.common.utils.PageUtils;
import com.cc.common.utils.ResponseData;
import com.cc.user.entity.UserEntity;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 *
 * @author leifengyang
 * @email leifengyang@gmail.com
 * @date 2020-12-11 15:43:43
 */
@RestController
@RequestMapping("bill/submitbill")
@Api(tags="报销")
public class SubmitBillController {

    @Autowired
    private SubmitBillNameService submitBillNameService;

    @Autowired
    private SubmitBillCertificatePictureService submitBillCPService;

    @Autowired
    private SubmitBillService submitBillService;



    @PostMapping("/updateBillSbStatusReasonById")
    @ApiOperation("后台根据报销id更改报销状态为失败")
    public ResponseData updateBillSbStatusReasonById(@RequestParam(required = true) Long id, @RequestParam(required = true) String reason) {
        SubmitBillEntity submitBillEntity = new SubmitBillEntity();
        submitBillEntity.setBillStatus(2);
        submitBillEntity.setReason(reason);
        submitBillService.update(submitBillEntity,new QueryWrapper<SubmitBillEntity>().eq("id",id));
        return ResponseData.success("修改成功",true);
    }

    @PostMapping("/updateBillCgStatusById")
    @ApiOperation("后台根据报销id更改报销状态为成功")
    public ResponseData updateBillCgStatusById(@RequestParam(required = true) Long id) {
        SubmitBillEntity submitBillEntity = new SubmitBillEntity();
        submitBillEntity.setBillStatus(1);
        submitBillService.update(submitBillEntity,new QueryWrapper<SubmitBillEntity>().eq("id",id));
        return ResponseData.success("修改成功",true);
    }


    @PostMapping("/getBillByStatusTime")
    @ApiOperation("后台根据报销状态时间获取报销记录")
    public ResponseData<PageUtils> getBillByStatusTime(@RequestParam(required = true) Map<String,Object> params) throws ParseException {
        // 获取开始时间和终止时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String startTimeStr = (String) params.get("startTime");
        String stopTimeStr = (String) params.get("stopTime");
        String searchMobile = (String) params.get("searchMobile");
        // 获取报销审核状态
        int billStatus = Integer.parseInt((String) params.get("billStatus"));

        List<WebBillVo> webBillVos = new ArrayList<>();
        // 获取bill list
        List<SubmitBillEntity> submitBillEntities = submitBillService.getBillList(billStatus, startTimeStr, stopTimeStr);
        for (SubmitBillEntity submitBillEntity : submitBillEntities){
            WebBillVo webBillVo = new WebBillVo();
            //获取报销凭证list
            List<SubmitBillCertificatePictureEntity> submitBillCPList = submitBillCPService.getSubmitBillList(submitBillEntity.getId());
            List<String> submitBillCPs = new ArrayList<>();
            for(SubmitBillCertificatePictureEntity submitBillCP:submitBillCPList){
                submitBillCPs.add(submitBillCP.getCertificatePicture());
            }

            UserEntity user = submitBillService.getUserByUid(submitBillEntity.getUid());

            webBillVo.setId(submitBillEntity.getId());
            webBillVo.setUid(submitBillEntity.getUid());
            webBillVo.setBillPrice(submitBillEntity.getBillPrice());
            webBillVo.setBillContent(submitBillEntity.getBillContent());
            webBillVo.setBillCertificate(submitBillEntity.getBillCertificate());
            webBillVo.setBillStatus(submitBillEntity.getBillStatus());
            webBillVo.setCreatetime(submitBillEntity.getCreatetime());
            webBillVo.setBillName(submitBillEntity.getBillName());
            webBillVo.setReason(submitBillEntity.getReason());
            webBillVo.setCertificatePictures(submitBillCPs);
            webBillVo.setBillName(submitBillEntity.getBillName());
            webBillVo.setNickname(user.getNickname());
            webBillVo.setMobile(user.getMobile());

            webBillVos.add(webBillVo);
        }

        int page = Integer.parseInt((String) params.get("page"));
        int limit = Integer.parseInt((String) params.get("limit"));
        int totalCount = webBillVos.size();
        List<WebBillVo> list = new ArrayList<>();
        for(int i = (page-1)*limit;i<page*limit;i++){
            if(i<=webBillVos.size()-1) {
                if (searchMobile != "" && searchMobile.equals(webBillVos.get(i).getMobile())){
                    list.add(webBillVos.get(i));
                }else if(searchMobile == ""){
                    list.add(webBillVos.get(i));
                }
            }
        }
        PageUtils pageUtils = new PageUtils(list, totalCount, limit, page);
        return ResponseData.success(pageUtils);
    }

    @GetMapping("/getSubmitBillByTime")
    @ApiOperation("后台根据日期、报销状态查看所有报销项")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "起始时间", paramType = "query", dataType = "Date", required = true),
            @ApiImplicitParam(name = "stopTime", value = "终止时间", paramType = "query", dataType = "Date", required = true),
            @ApiImplicitParam(name = "billStatus", value = "报销状态0待审核1成功2失败", paramType = "query", dataType = "String", required = true, allowableValues = "0,1,2")
    })
    public ResponseData<List<SubmitBillVo>> getSubmitBillByTime(@RequestParam("startTime") Date startTime, @RequestParam("stopTime") Date stopTime, @RequestParam("billStatus") Integer billStatus, HttpSession session){
        UserEntity user = (UserEntity) session.getAttribute("loginuser");
        Long uid = user.getUid();

        List<SubmitBillVo> billList = submitBillService.getSubmitBillByTime(uid,startTime,stopTime,billStatus);
        return ResponseData.success(billList);
    }

    @PostMapping("/uploadSubmitBill")
    @ApiOperation("提交报销审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "billPrice", value = "报销金额", paramType = "query", dataType = "BigDecimal", required = true),
            @ApiImplicitParam(name = "billContent", value = "详细内容", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "billCertificate", value = "报销凭证src", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "sbnid", value = "报销项目id", paramType = "query", dataType = "Long", required = true)
    })
    public ResponseData uploadSubmitBill(@RequestParam("billPrice") BigDecimal billPrice,
                                         @RequestParam("billContent")String billContent,
                                         @RequestParam("billCertificate")String billCertificate,
                                         @RequestParam("sbnid")Long sbnid,
                                         @ApiParam("照片src List") @RequestBody(required = true) List<String> certificate_pictures,
                                         HttpSession session){
        SubmitBillNameEntity submitBillNameEntity = submitBillNameService.getById(sbnid);
        if (submitBillNameEntity == null)   return ResponseData.success("提交信息不完整",false);
        UploadSubmitBillVo uploadSubmitBillVo = new UploadSubmitBillVo();
        uploadSubmitBillVo.setBillPrice(billPrice);
        uploadSubmitBillVo.setBillContent(billContent);
        uploadSubmitBillVo.setBillCertificate(billCertificate);
        uploadSubmitBillVo.setBillName(submitBillNameEntity.getBillName());
        uploadSubmitBillVo.setCertificate_pictures(certificate_pictures);
        
        if (uploadSubmitBillVo.judge()){
            return ResponseData.success("提交信息不完整",false);
        }
        UserEntity user = (UserEntity) session.getAttribute("loginuser");
        Long uid = user.getUid();

        SubmitBillEntity submitBillEntity = new SubmitBillEntity();
        submitBillEntity.setUid(uid);
        submitBillEntity.setBillPrice(uploadSubmitBillVo.getBillPrice());
        submitBillEntity.setBillContent(uploadSubmitBillVo.getBillContent());
        submitBillEntity.setBillCertificate(uploadSubmitBillVo.getBillCertificate());
        submitBillEntity.setBillStatus(0);
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        submitBillEntity.setCreatetime(sim.format(new Date()));
        submitBillEntity.setBillName(uploadSubmitBillVo.getBillName());

        // 向报销表插入一条记录并返回id
        Long cid = submitBillService.insertSubmitBill(submitBillEntity);

        // 向报销凭证照片表插入记录
        List<SubmitBillCertificatePictureEntity> list= new ArrayList<>();
        SubmitBillCertificatePictureEntity certificatePictureEntity;
        for (String certificate_Picture:uploadSubmitBillVo.getCertificate_pictures()) {
            certificatePictureEntity = new SubmitBillCertificatePictureEntity();
            certificatePictureEntity.setCid(cid);
            certificatePictureEntity.setCertificatePicture(certificate_Picture);
            list.add(certificatePictureEntity);
        }
        submitBillCPService.saveBatch(list);

        return ResponseData.success("提交审核成功",true);
    }

    @PostMapping("/getSubmitBillByBid")
    @ApiOperation("通过报销id查看报销详细信息")
    public ResponseData<SubmitBillEntity> getSubmitBillByBid(@RequestParam("id") Long id){
        SubmitBillEntity submitBillDetail = submitBillService.getById(id);
        if(submitBillDetail == null) ResponseData.success(null);
        SubmitBillDetailEntity submitBillDetailEntity = new SubmitBillDetailEntity();
        submitBillDetailEntity.setId(submitBillDetail.getId());
        submitBillDetailEntity.setUid(submitBillDetail.getUid());
        submitBillDetailEntity.setBillPrice(submitBillDetail.getBillPrice());
        submitBillDetailEntity.setBillContent(submitBillDetail.getBillContent());
        submitBillDetailEntity.setBillCertificate(submitBillDetail.getBillCertificate());
        submitBillDetailEntity.setBillStatus(submitBillDetail.getBillStatus());
        submitBillDetailEntity.setCreatetime(submitBillDetail.getCreatetime());
        submitBillDetailEntity.setBillName(submitBillDetail.getBillName());

        List<SubmitBillCertificatePictureEntity> SubmitBillCertificatePictureList = submitBillCPService.list(new QueryWrapper<SubmitBillCertificatePictureEntity>().eq("cid", id));
        ArrayList<String> list = new ArrayList<>();
        for (SubmitBillCertificatePictureEntity s:SubmitBillCertificatePictureList){
            list.add(s.getCertificatePicture());
        }
        submitBillDetailEntity.setCertificate_pictures(list);
        return ResponseData.success(submitBillDetailEntity);
    }


    @PostMapping("/getBills")
    @ApiOperation("根据日期、报销状态查看获取报销记录")
    public ResponseData<List<WebBillVo>> getBills(SubmitSelectConditionVo submitSelectConditionVo,HttpSession session) throws ParseException {
        UserEntity userEntity = (UserEntity) session.getAttribute("loginuser");
        Long uid = userEntity.getUid();
        // 获取开始时间和终止时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long startTimeLong = submitSelectConditionVo.getStartTime();
        Long stopTimeLong = submitSelectConditionVo.getStopTime();
        String startTime = null;
        String stopTime = null;
        if (startTimeLong != null)   startTime = simpleDateFormat.format(startTimeLong);
        if (stopTimeLong != null)   stopTime = simpleDateFormat.format(stopTimeLong);
        // 获取报销审核状态
        Integer billStatus = submitSelectConditionVo.getBillStatus();

        List<WebBillVo> webBillVos = new ArrayList<>();
        List<SubmitBillEntity> submitBillEntities;
        if (startTime != null && stopTime != null && billStatus != null) {
            submitBillEntities = submitBillService.list(new QueryWrapper<SubmitBillEntity>().eq("uid",uid).eq("bill_status", billStatus).between("createtime", startTime, stopTime));
        }else if (billStatus != null){
            submitBillEntities = submitBillService.list(new QueryWrapper<SubmitBillEntity>().eq("uid",uid).eq("bill_status", billStatus));
        }else{
            submitBillEntities = submitBillService.list(new QueryWrapper<SubmitBillEntity>().eq("uid",uid));
        }
        for (SubmitBillEntity submitBillEntity : submitBillEntities){
            WebBillVo webBillVo = new WebBillVo();
            //获取报销凭证list
            List<SubmitBillCertificatePictureEntity> submitBillCPList = submitBillCPService.getSubmitBillList(submitBillEntity.getId());
            List<String> submitBillCPs = new ArrayList<>();
            for(SubmitBillCertificatePictureEntity submitBillCP:submitBillCPList){
                submitBillCPs.add(submitBillCP.getCertificatePicture());
            }

            UserEntity user = submitBillService.getUserByUid(submitBillEntity.getUid());

            webBillVo.setId(submitBillEntity.getId());
            webBillVo.setUid(submitBillEntity.getUid());
            webBillVo.setBillPrice(submitBillEntity.getBillPrice());
            webBillVo.setBillCertificate(submitBillEntity.getBillCertificate());
            webBillVo.setBillStatus(submitBillEntity.getBillStatus());
            webBillVo.setBillContent(submitBillEntity.getBillContent());
            webBillVo.setCreatetime(submitBillEntity.getCreatetime());
            webBillVo.setBillName(submitBillEntity.getBillName());
            webBillVo.setReason(submitBillEntity.getReason());
            webBillVo.setCertificatePictures(submitBillCPs);
            webBillVo.setBillName(submitBillEntity.getBillName());
            webBillVo.setNickname(user.getNickname());
            webBillVo.setMobile(user.getMobile());

            webBillVos.add(webBillVo);
        }
        return ResponseData.success(webBillVos);
    }

    /**
     * 列表
     */

//
//    /**
//     * 信息
//     */
//    @GetMapping("/info/{id}")
//    public R info(@PathVariable("id") Long id){
//		SubmitBillEntity submitBill = submitBillService.getById(id);
//
//        return R.ok().put("submitBill", submitBill);
//    }
//
//    /**
//     * 保存
//     */
//    @PostMapping("/save")
//    public R save(@RequestBody SubmitBillEntity submitBill){
//		submitBillService.save(submitBill);
//
//        return R.ok();
//    }
//
//    /**
//     * 修改
//     */
//    @PostMapping("/update")
//    public R update(@RequestBody SubmitBillEntity submitBill){
//		submitBillService.updateById(submitBill);
//
//        return R.ok();
//    }
//
//    /**
//     * 删除
//     */
//    @PostMapping("/delete")
//    public R delete(@RequestBody Long[] ids){
//		submitBillService.removeByIds(Arrays.asList(ids));
//
//        return R.ok();
//    }



}
